let util = require('../../../../common/util/util.js')
let text = require('../../../../common/util/text.js')
const app = getApp()

const xAudio = wx.createInnerAudioContext({
    obeyMuteSwitch: false,
    success: function (res) {
        console.log(res)
        console.log("开启静音模式下播放音乐的功能");
    },
    fail: function (err) {
        console.log(err)
        console.log("静音设置失败");
    },
});

/* 背景音乐 */
const xBackMusic = wx.getBackgroundAudioManager();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    week:'',
    treatment_item_id:'',
    action_list:[],
    type:'',
    current:-1,
    count:0,
    status:false,
    class:'',
    PracticeStatus:false,
    showtips:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
      let that =this;
      that.setData({
        week:Number(options.week),
        treatment_item_id:options.treatment_item_id,
        type:Number(options.type),
        status:options.status,
        class:options.num==12 ? 2:1
      })
      
      that.xInit(1)
  },
  
  /**
   *   监听页面初次渲染完成
   */
  onReady() {
    xBackMusic.src='1'
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    let that =this;
    // wx.setNavigationBarTitle({
    //   title: this.data.class==2?'正念练习':'放松练习',
    // })
    // that.xChildReload()
  },
  xChildReload: function () {
    var pages = getCurrentPages();//当前页面栈
    if (pages.length > 1) {
      var beforePage = pages[pages.length - 2];//获取上一个页面实例对象
       beforePage.xInfo();//触发父页面中的方法
    }
  },
  // 音频播放
  xToplay:function(e){
    let index = e.currentTarget.dataset.index
    if(xBackMusic.src!=e.currentTarget.dataset.file){
      xAudio.src = e.currentTarget.dataset.file
      xBackMusic.src = e.currentTarget.dataset.file
      xBackMusic.title = e.currentTarget.dataset.name
      if(this.data.current != -1){
        this.setData({
          [`action_list[${this.data.current}].play`]:false
        })
      }
    }
    this.setData({
      current:index,
      [`action_list[${index}].play`]:true
    })
    this.xAudioPlay(index)
  },
  // 音频暂停
  xTostop:function(e){
    let index = e.currentTarget.dataset.index
    this.setData({
      [`action_list[${index}].play`]:false
    })
    this.xAudioStop(index)
  },
  xAudioPlay: function (index) {
    let that = this
    xBackMusic.play()
    var index =index;
    setTimeout(() => {
        xBackMusic.currentTime
        xBackMusic.onTimeUpdate(() => {
            let xNowTime = xBackMusic.duration - xBackMusic.currentTime
            let time = that.formatSeconds(xNowTime)
            that.setData({
              [`action_list[${index}].countdown`]:time
            })
        })
        xBackMusic.onEnded(()=>{
           that.setData({
             current:-1,
             [`action_list[${index}].countdown`]:that.data.action_list[index].playback_duration
           })
           that.xToadd()
           that.xInit(1)
        })
    }, 1000)
},
formatSeconds(value) {
    var theTime = parseInt(value);// 秒
    var middle= 0;// 分
    var hour= 0;// 小时
    if(theTime > 60) {undefined
        middle= parseInt(theTime/60);
        theTime = parseInt(theTime%60);
        if(middle> 60) {undefined
            hour= parseInt(middle/60);
            middle= parseInt(middle%60);
        }
    }
    let h = parseInt(hour) > 0 ? parseInt(hour) + ":"  : ''
    let m = parseInt(middle) > 9 ? parseInt(middle) : '0' + parseInt(middle)
    let s = parseInt(theTime) > 9 ? parseInt(theTime) : '0' + parseInt(theTime);
    let result = h + m + ':' + s
    return result;
},

xAudioStop: function () {
    let that = this
    xBackMusic.pause()
},
// 手动打卡
punchClock:function(){
    let that =this;
    wx.showModal({
      title:'提示',
      content:'你已经自行完成了练习吗？',
      success (res) {
        if (res.confirm) {
          that.xToadd()
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  // 新增记录
  xToadd:function(){
    let that =this;
    wx.showLoading({
      title: '保存中',
    })
    if( that.data.count<5){
      let _dataObj = {
        treatment_item_id: that.data.treatment_item_id,
      }
      wx.cloud.callFunction({
        name: 'audio_video_practice',
        data: {
          action: "add_practice_punching",
          dataObj: _dataObj
        }
      }).then(res => {
          wx.hideLoading()
          that.xInit(2)
          that.xChildReload()
      })
    }
  },
  xInit:function(type){
    let that =this;
    let _dataObj = {
      week: that.data.week,
      treatment_item_id: that.data.treatment_item_id,
      class: Number(that.data.class), //1:放松练习
      file_type:2 //1:视频,2:音频
    }
    wx.cloud.callFunction({
      name: 'audio_video_practice',
      data: {
        action: "get_audio_video_list",
        dataObj: _dataObj
      }
    }).then(res => {
      var dates =new Date()
      if(res.result.length>0){
        that.setData({
          count:res.result[0].practice_punching_count,
        })
      }
      for(let index in res.result){
        res.result[index].countdown=res.result[index].playback_duration
      }
      if(type==1){
        that.setData({
          action_list:res.result
        })
      }
    })
    that.xToPracticeStatus()
  },
  // 动作详情
  xToInfo:function(e){
      let that =this;
      let action_id = e.currentTarget.dataset.action_id
      let name =e.currentTarget.dataset.name
      wx.navigateTo({
        url: '/subtool/pages/action/details/index?week='+that.data.week+'&action_id='+ action_id+'&treatment_item_id='+that.data.treatment_item_id+'&type='+that.data.type+'&name='+name,
      })
  },
  
xToPracticeStatus:function(){
  let that =this;
  wx.cloud.callFunction({
    name: 'practice_help',
    data: {
      action: "get_practice_help_status",
      dataObj: {
        num:that.data.class==2?3:8
      }
    }
  }).then(res => {
    for(let index in res.result){
      if(res.result[index]._id==1){
        that.setData({
          PracticeStatus:res.result[index].status
        })
      }
    }
  })
},
xTosetM:function(){
  let that=this
  wx.setStorageSync(this.data.treatment_item_id, this.data.treatment_item_id)
  let _dataObj = {
    num:that.data.class==2?3:8,//练习任务类型数值
    type:1,//1:练习说明
  }
  wx.cloud.callFunction({
    name: 'practice_help',
    data: {
      action: "get_practice_help",
      dataObj: _dataObj
    }
  }).then(res => {
    res.result[0].content=text.text(res.result[0].content)
    this.setData({
      showtips:!this.data.showtips,
      practice_help:res.result[0]
    })
  })
    
},
  // xToTips:function(){
  //   wx.showModal({
  //     title: "提示",
  //     content: "此项任务今天已完成，请明天继续",
  //     showCancel: false,
  //     confirmText:'好的'
  //   })
  // },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})